package com.aaa.realm;

import com.aaa.entity.Permission;
import com.aaa.entity.User;
import com.aaa.service.impl.PermissionServiceIpl;
import com.aaa.service.impl.UserServiceImpl;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;


public class MyRealm extends AuthorizingRealm {
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private PermissionServiceIpl permissionService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        User user = (User) principals.getPrimaryPrincipal();
        //根据id查询该用户具有的权限
        List<Permission> permissions= permissionService.selectByUserId(user.getUserid());
        if(permissions.size()>0){
            SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
            List<String> list=permissions.stream().map(item->item.getPercode()).collect(Collectors.toList());
            info.addStringPermissions(list);
            return info;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取输入账号
        Object username = token.getPrincipal();
        //调用UserService中根据名称查询用户信息
        User user=userService.selectByName(username);
        //判断user是否为null
        if(user!=null){
            ByteSource salt=ByteSource.Util.bytes(user.getSalt());
            SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user,user.getUserpwd(),salt,this.getName());
            return info;
        }
        return null;
    }
}
